import React, { useEffect, useState } from 'react';
import { X } from 'lucide-react';
interface QuizQuestion {
  id: number;
  question: string;
  options: {
    id: string;
    text: string;
    value: string;
  }[];
}
interface QuizResult {
  title: string;
  description: string;
  ritual: string;
  products: {
    id: string;
    name: string;
    category: string;
  }[];
}
interface RitualQuizProps {
  isOpen: boolean;
  onClose: () => void;
}
export function RitualQuiz({
  isOpen,
  onClose
}: RitualQuizProps) {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<Record<number, string>>({});
  const [showResults, setShowResults] = useState(false);
  const [result, setResult] = useState<QuizResult | null>(null);
  const [animateIn, setAnimateIn] = useState(false);
  // Quiz questions
  const questions: QuizQuestion[] = [{
    id: 1,
    question: 'What time of day do you struggle with the most?',
    options: [{
      id: 'morning',
      text: 'Morning - I have trouble getting energized',
      value: 'morning'
    }, {
      id: 'day',
      text: 'During the day - I feel scattered or unfocused',
      value: 'day'
    }, {
      id: 'evening',
      text: 'Evening - I have trouble unwinding',
      value: 'evening'
    }, {
      id: 'night',
      text: 'Night - I have difficulty falling or staying asleep',
      value: 'night'
    }]
  }, {
    id: 2,
    question: "Which best describes your skin's current state?",
    options: [{
      id: 'dry',
      text: 'Dry and in need of hydration',
      value: 'dry'
    }, {
      id: 'dull',
      text: 'Dull and lacking radiance',
      value: 'dull'
    }, {
      id: 'stressed',
      text: 'Stressed and reactive',
      value: 'stressed'
    }, {
      id: 'balanced',
      text: 'Generally balanced but looking to maintain',
      value: 'balanced'
    }]
  }, {
    id: 3,
    question: 'What is your main wellness goal right now?',
    options: [{
      id: 'stress',
      text: 'Reduce stress and anxiety',
      value: 'stress'
    }, {
      id: 'sleep',
      text: 'Improve sleep quality',
      value: 'sleep'
    }, {
      id: 'energy',
      text: 'Increase energy and focus',
      value: 'energy'
    }, {
      id: 'balance',
      text: 'Find more balance in daily life',
      value: 'balance'
    }]
  }, {
    id: 4,
    question: 'How much time can you realistically dedicate to a daily ritual?',
    options: [{
      id: 'minimal',
      text: '5 minutes or less',
      value: 'minimal'
    }, {
      id: 'short',
      text: '5-15 minutes',
      value: 'short'
    }, {
      id: 'medium',
      text: '15-30 minutes',
      value: 'medium'
    }, {
      id: 'extended',
      text: '30+ minutes',
      value: 'extended'
    }]
  }, {
    id: 5,
    question: 'Which scent profile do you find most calming?',
    options: [{
      id: 'floral',
      text: 'Floral (rose, jasmine, lavender)',
      value: 'floral'
    }, {
      id: 'earthy',
      text: 'Earthy (sandalwood, vetiver, patchouli)',
      value: 'earthy'
    }, {
      id: 'citrus',
      text: 'Citrus (bergamot, neroli, grapefruit)',
      value: 'citrus'
    }, {
      id: 'herbal',
      text: 'Herbal (chamomile, rosemary, mint)',
      value: 'herbal'
    }]
  }];
  // Quiz results
  const results: Record<string, QuizResult> = {
    morning: {
      title: 'Morning Glow Ritual',
      description: 'Start your day with intention and radiance. This gentle morning routine combines skincare and mindfulness for a balanced beginning.',
      ritual: 'the-ritual',
      products: [{
        id: 'sk-002',
        name: 'Vitamin C Brightening Serum',
        category: 'skincare'
      }, {
        id: 'wl-002',
        name: 'Relaxation Tea Blend',
        category: 'wellness'
      }, {
        id: 'sk-004',
        name: 'Green Tea Cleansing Oil',
        category: 'skincare'
      }]
    },
    evening: {
      title: 'Evening Renewal Ritual',
      description: "Unwind and restore with this evening practice. Release the day's tension and prepare your skin for overnight renewal.",
      ritual: 'the-ritual',
      products: [{
        id: 'wl-001',
        name: 'Lavender Sleep Mist',
        category: 'wellness'
      }, {
        id: 'sk-006',
        name: 'Nourishing Face Oil',
        category: 'skincare'
      }, {
        id: 'wl-005',
        name: 'Jade Facial Roller',
        category: 'wellness'
      }]
    },
    reset: {
      title: 'Weekly Reset Ritual',
      description: 'Take time for deeper self-care with this weekly ritual. Exfoliate, mask, and reset both your skin and mind.',
      ritual: 'the-ritual',
      products: [{
        id: 'sk-007',
        name: 'Gentle Exfoliating Scrub',
        category: 'skincare'
      }, {
        id: 'sk-003',
        name: 'Overnight Hydration Mask',
        category: 'skincare'
      }, {
        id: 'wl-004',
        name: 'Aromatherapy Diffuser',
        category: 'wellness'
      }]
    }
  };
  // Set animation on mount
  useEffect(() => {
    if (isOpen) {
      // Small delay to ensure the component is rendered before animation starts
      setTimeout(() => setAnimateIn(true), 10);
    } else {
      setAnimateIn(false);
    }
  }, [isOpen]);
  // Handle closing with animation
  const handleClose = () => {
    setAnimateIn(false);
    // Wait for animation to complete before actually closing
    setTimeout(() => {
      onClose();
      // Reset quiz state
      setCurrentQuestion(0);
      setAnswers({});
      setShowResults(false);
      setResult(null);
    }, 300);
  };
  // Handle answer selection
  const handleAnswer = (answerId: string) => {
    setAnswers(prev => ({
      ...prev,
      [questions[currentQuestion].id]: answerId
    }));
    // Move to next question or show results
    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(prev => prev + 1);
    } else {
      calculateResult();
    }
  };
  // Calculate quiz result based on answers
  const calculateResult = () => {
    // Simple algorithm - just use the answer to the first question to determine result
    // In a real app, you would have a more sophisticated algorithm
    const firstAnswer = answers[1];
    if (firstAnswer === 'morning' || firstAnswer === 'day') {
      setResult(results.morning);
    } else if (firstAnswer === 'evening') {
      setResult(results.evening);
    } else {
      setResult(results.reset);
    }
    setShowResults(true);
  };
  // If not open, don't render anything
  if (!isOpen) return null;
  return <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className={`absolute inset-0 bg-black transition-opacity duration-300 ${animateIn ? 'opacity-50' : 'opacity-0'}`} onClick={handleClose}></div>
      {/* Quiz Modal */}
      <div className={`relative bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto transition-all duration-300 ${animateIn ? 'opacity-100 scale-100' : 'opacity-0 scale-95'}`}>
        {/* Close button */}
        <button onClick={handleClose} className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 transition-colors" aria-label="Close quiz">
          <X size={24} />
        </button>
        <div className="p-6 md:p-8">
          {!showResults ? <>
              {/* Quiz header */}
              <div className="text-center mb-8">
                <h2 className="font-serif text-2xl md:text-3xl text-[#4a4a4a] mb-2">
                  Discover Your Perfect Ritual
                </h2>
                <p className="text-gray-600">
                  Answer a few questions to find personalized recommendations
                </p>
              </div>
              {/* Progress bar */}
              <div className="w-full bg-[#f3f0eb] h-2 rounded-full mb-8">
                <div className="bg-[#4a6b60] h-2 rounded-full transition-all duration-300" style={{
              width: `${(currentQuestion + 1) / questions.length * 100}%`
            }}></div>
              </div>
              {/* Question */}
              <h3 className="font-medium text-xl mb-6">
                {questions[currentQuestion].question}
              </h3>
              {/* Answer options */}
              <div className="space-y-4">
                {questions[currentQuestion].options.map(option => <button key={option.id} onClick={() => handleAnswer(option.value)} className="w-full text-left p-4 border border-[#e8e5e0] rounded-md hover:border-[#4a6b60] hover:bg-[#f8f5f0] transition-colors">
                    {option.text}
                  </button>)}
              </div>
              {/* Question counter */}
              <div className="mt-8 text-center text-sm text-gray-500">
                Question {currentQuestion + 1} of {questions.length}
              </div>
            </> : <>
              {/* Results */}
              <div className="text-center mb-8">
                <div className="inline-block bg-[#f3f0eb] p-3 rounded-full mb-4">
                  <div className="bg-[#4a6b60] text-white w-16 h-16 rounded-full flex items-center justify-center">
                    <span className="font-serif text-2xl">✓</span>
                  </div>
                </div>
                <h2 className="font-serif text-2xl md:text-3xl text-[#4a4a4a] mb-2">
                  Your Perfect Match
                </h2>
                <p className="text-gray-600">
                  Based on your answers, we've found your ideal ritual
                </p>
              </div>
              {result && <div className="bg-[#f8f5f0] p-6 rounded-lg mb-8">
                  <h3 className="font-serif text-xl text-[#4a6b60] mb-2">
                    {result.title}
                  </h3>
                  <p className="text-sm mb-6">{result.description}</p>
                  <h4 className="font-medium text-sm uppercase tracking-wider mb-3">
                    Recommended Products
                  </h4>
                  <ul className="space-y-3 mb-6">
                    {result.products.map(product => <li key={product.id} className="flex items-center">
                        <span className="w-2 h-2 bg-[#4a6b60] rounded-full mr-2"></span>
                        <span>{product.name}</span>
                      </li>)}
                  </ul>
                  <button onClick={handleClose} className="w-full bg-[#4a6b60] hover:bg-[#3d5a50] text-white py-3 rounded-md transition-colors">
                    Explore This Ritual
                  </button>
                </div>}
              <div className="text-center">
                <button onClick={() => {
              setCurrentQuestion(0);
              setAnswers({});
              setShowResults(false);
              setResult(null);
            }} className="text-[#4a6b60] hover:underline">
                  Take the quiz again
                </button>
              </div>
            </>}
        </div>
      </div>
    </div>;
}